package com.example.hello.mapper;

import com.example.hello.pojo.Book;
import com.example.hello.pojo.UserBook;
import org.apache.ibatis.annotations.*;

import java.util.Date;
import java.util.List;

@Mapper
public interface UserBookMapper {

    /**
     * 插入借书记录
     */
    @Insert("INSERT INTO user_book (user_id, book_id, borrow_date,max_borrow_day, created_at, updated_at) " +
            "VALUES (#{userId}, #{bookId}, #{borrowDate},#{maxBorrowBookDay}, #{createdAt}, #{updatedAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertUserBook(UserBook userBook);

    /**
     * 查询当前用户未归还的借阅记录数量
     */
    @Select("SELECT COUNT(*) FROM user_book WHERE user_id = #{userId} AND return_date IS NULL")
    int countActiveBorrows(@Param("userId") Long userId);

    /**
     * 查询当前用户是否已借阅指定图书且尚未归还
     */
    @Select("SELECT * FROM user_book WHERE user_id = #{userId} AND book_id = #{bookId} AND return_date IS NULL LIMIT 1")
    UserBook getActiveBorrowForBook(@Param("userId") Long userId, @Param("bookId") Integer bookId);

    /**
     * 根据用户ID查询其借阅的图书列表
     * SQL 通过 user_book 与 book 表关联，返回图书详情
     */
    @Select("select b.* ,ub.borrow_date operateDate " +
            "from book b " +
            "left join user_book ub on b.id = ub.book_id " +
            "where ub.user_id = #{userId} and return_date is null " +
            "order by ub.updated_at desc")
    List<Book> getBorrowedBooksByUserId(@Param("userId") Long userId);

    /**
     * 更新借书记录的归还时间，将 return_date 更新为当前时间
     * 只更新未归还（return_date 为 NULL）的记录
     *
     * @param userId 用户ID
     * @param bookId 图书ID
     * @param returnDate 归还时间（通常为当前时间）
     * @return 受影响的记录数
     */
    @Update("UPDATE user_book SET return_date = #{returnDate}, updated_at = NOW() " +
            "WHERE user_id = #{userId} AND book_id = #{bookId} AND return_date IS NULL")
    int updateReturnDate(@Param("userId") Long userId,
                         @Param("bookId") Integer bookId,
                         @Param("returnDate") Date returnDate);


    @Select("select b.* ,ub.borrow_date operateDate " +
            "from book b " +
            "left join user_book ub on b.id = ub.book_id " +
            "where ub.user_id = #{userId} " +
            "order by ub.borrow_date desc")
    List<Book> getAllBorrowedBooksByUserId(Long userId);

    @Select("select b.* ,ub.return_date operateDate " +
            "from book b " +
            "left join user_book ub on b.id = ub.book_id " +
            "where ub.user_id = #{userId} and return_date is not null " +
            "order by ub.return_date desc")
    List<Book> getAllReturnedBooksByUserId(Long userId);
}